package com.time.store.auth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.time.store.auth.entity.bo.Roles;
import com.time.store.auth.entity.bo.UserRoles;
import com.time.store.auth.entity.dto.AddUserSetRoleReq;
import com.time.store.auth.entity.dto.RolePageQueryReq;
import com.time.store.auth.entity.vo.RoleListRes;
import com.time.store.auth.service.RolesService;
import com.time.store.auth.service.UserRolesService;
import com.time.store.core.util.AssertUtil;
import com.time.store.core.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 角色控制器
 *
 * @description: 角色控制器
 * @menu 角色
 */
@RequestMapping("/api/auth/role")
@RestController
public class RoleController {
    @Autowired
    private RolesService rolesService;

    /**
     * 保存角色
     *
     * @param roles
     * @status done
     */
    @PostMapping("")
    public void save(@RequestBody @Validated Roles roles) {
        roles.setStoreId(AuthUtil.getCurrStoreId());
        rolesService.save(roles);
    }

    /**
     * 修改角色
     *
     * @param roles
     * @status done
     */
    @PutMapping("/{id}")
    public void update(@RequestBody @Validated Roles roles, @PathVariable("id") Integer id) {
        roles.setId(id);
        roles.setStoreId(null);
        roles.setCreateTime(null);
        roles.setUpdateTime(null);
        rolesService.updateById(roles);
    }

    /**
     * 删除角色
     *
     * @status done
     */
    @DeleteMapping("/{id}")
    public void remove(@PathVariable("id") Integer id) {
        AssertUtil.isFalse(id == 1,"初始化角色不能删除");
        rolesService.removeById(id);
    }

    /**
     * 分页查询角色
     *
     * @status done
     */
    @GetMapping("/page")
    public Page<Roles> page(@Validated RolePageQueryReq rolePageQueryReq) {
        return rolesService.pageRole(rolePageQueryReq);
    }

    /**
     * 根据用户id查询所有角色
     * @status done
     * @return
     */
    @GetMapping("/listByUserId")
    public List<RoleListRes> listByUserId(@RequestParam Integer userId) {
        return rolesService.listByUserId(userId);
    }


    /**
     * 根据用户id设置所有角色
     * @status done
     * @return
     */
    @PutMapping("/updateUserRole")
    public Boolean updateUserRole(@RequestBody @Validated AddUserSetRoleReq addUserSetRoleReq){
        return rolesService.updateUserRole(addUserSetRoleReq);

    }

}
